import { ErrorViewer } from "@/component/ErrorViewer";
import { clearLoginInfo, getLoginInfo } from "@/hooks/useLoginInfo";
import axios, { AxiosError, AxiosHeaders } from "axios";

axios.interceptors.request.use(async (config) => {
  if (config.url?.startsWith(__API_URL_BASE__) && config.headers instanceof AxiosHeaders) {
    const token = await getLoginInfo('token').catch(e => null)
    config.headers.set('Authorization', token)
  }
  return config;
});

axios.interceptors.response.use((response) => {
  if (!response.config.url?.startsWith(__API_URL_BASE__))
    return response;
  switch ('' + response.data?.code) {
    case '401':
      clearLoginInfo();
      break;
    case '500':
      const errStr = JSON.stringify(response, null, 2)
      ErrorViewer.addError(errStr)
      response.data.msg = response.data.msg?.substring(0, 120);
      break;
  }
  return response;
}, (error: AxiosError) => {
  if (!error.config?.url?.startsWith(__API_URL_BASE__))
    return error;
  switch (error.response?.status) {
    case 401:
      clearLoginInfo();
      break;
  }
  return Promise.reject(error);
});